<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pomodoro Timer</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 2rem;
            background-color: #f0f0f0;
        }
        .container {
            text-align: center;
            background-color: white;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            margin-bottom: 2rem;
            box-sizing: border-box;
        }
        #timer {
            font-size: 4rem;
            margin-bottom: 1rem;
        }
        button, select, input {
            font-size: 1rem;
            padding: 0.5rem 1rem;
            margin: 0.5rem;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        #startBtn {
            background-color: #4CAF50;
            color: white;
        }
        #startBtn:hover {
            background-color: #45a049;
        }
        #resetBtn, #endBtn {
            background-color: #f44336;
            color: white;
        }
        #resetBtn:hover, #endBtn:hover {
            background-color: #da190b;
        }
        select {
            background-color: #3498db;
            color: white;
            -webkit-appearance: none;
            padding: 0.5rem 1rem;
            margin: 0.5rem;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        select:hover {
            background-color: #2980b9;
        }
        #goalInput {
            width: calc(100% - 1.5em);
            padding: 0.5rem;
            margin-bottom: 1rem;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-sizing: border-box;
        }
        #sessionLog {
            width: 100%;
            max-width: 800px;
            margin-top: 2rem;
            overflow-x: auto;
        }
        #sessionLog table {
            width: 100%;
            border-collapse: collapse;
        }
        #sessionLog th, #sessionLog td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        #sessionLog th {
            background-color: #f2f2f2;
        }
        #jsonOutput {
            width: 100%;
            height: 200px;
            margin-top: 2rem;
            font-family: monospace;
        }
        .deleteBtn {
            background-color: transparent;
            border: none;
            color: #f44336;
            cursor: pointer;
            font-size: 1.2rem;
            padding: 0.2rem 0.5rem;
        }
        .deleteBtn:hover {
            color: #da190b;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Pomodoro Timer</h1>
        <input type="text" id="goalInput" placeholder="Enter your goal for this session" required>
        <div id="timer">25:00</div>
        <select id="durationSelect">
            <option value="5">5 minutes</option>
            <option value="10">10 minutes</option>
            <option value="15">15 minutes</option>
            <option value="20">20 minutes</option>
            <option value="25" selected>25 minutes</option>
            <option value="30">30 minutes</option>
            <option value="45">45 minutes</option>
            <option value="60">60 minutes</option>
        </select>
        <br>
        <button id="startBtn">Start</button>
        <button id="resetBtn">Reset</button>
        <button id="endBtn">End Session</button>
    </div>

    <div id="sessionLog">
        <h2>Session Log</h2>
        <table>
            <thead>
                <tr>
                    <th>Goal</th>
                    <th>Start Time</th>
                    <th>End Time</th>
                    <th>Duration</th>
                    <th>Pauses</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody id="sessionLogBody"></tbody>
        </table>
    </div>

    <textarea id="jsonOutput" readonly></textarea>

    <script>
        const timerDisplay = document.getElementById('timer');
        const startBtn = document.getElementById('startBtn');
        const resetBtn = document.getElementById('resetBtn');
        const endBtn = document.getElementById('endBtn');
        const durationSelect = document.getElementById('durationSelect');
        const goalInput = document.getElementById('goalInput');
        const sessionLogBody = document.getElementById('sessionLogBody');
        const jsonOutput = document.getElementById('jsonOutput');

        let startTime;
        let timeLeft = 25 * 60; // Default to 25 minutes in seconds
        let isRunning = false;
        let duration = 25 * 60; // Default duration in seconds
        let currentSession = null;
        let sessions = [];

        // Check if localStorage is available
        function isLocalStorageAvailable() {
            try {
                localStorage.setItem('test', 'test');
                localStorage.removeItem('test');
                return true;
            } catch (e) {
                return false;
            }
        }

        // Load sessions from storage
        function loadSessions() {
            if (isLocalStorageAvailable()) {
                const storedSessions = localStorage.getItem('pomodoroSessions');
                if (storedSessions) {
                    sessions = JSON.parse(storedSessions);
                }
            } else {
                console.warn('localStorage is not available. Session data will not persist.');
            }
            updateSessionLog();
        }

        loadSessions();

        function formatDate(date) {
            return new Date(date).toLocaleString('en-US', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: true
            }).replace(',', '');
        }

        function updateDisplay() {
            const minutes = Math.floor(timeLeft / 60);
            const seconds = timeLeft % 60;
            timerDisplay.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }

        function startTimer() {
            if (!isRunning) {
                if (!goalInput.value) {
                    alert('Please enter a goal for this session.');
                    return;
                }
                isRunning = true;
                startBtn.textContent = 'Pause';
                durationSelect.disabled = true;
                goalInput.disabled = true;
                if (!currentSession) {
                    currentSession = {
                        goal: goalInput.value,
                        startTime: new Date().toISOString(),
                        endTime: null,
                        duration: 0,
                        pauses: []
                    };
                } else {
                    currentSession.pauses[currentSession.pauses.length - 1].resumeTime = new Date().toISOString();
                }
                startTime = Date.now() - ((duration - timeLeft) * 1000);
                requestAnimationFrame(updateTimer);
            } else {
                isRunning = false;
                startBtn.textContent = 'Resume';
                currentSession.pauses.push({
                    pauseTime: new Date().toISOString(),
                    resumeTime: null
                });
            }
        }

        function updateTimer() {
            if (isRunning) {
                const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
                timeLeft = duration - elapsedTime;

                if (timeLeft <= 0) {
                    timeLeft = 0;
                    isRunning = false;
                    startBtn.textContent = 'Start';
                    durationSelect.disabled = false;
                    goalInput.disabled = false;
                    endSession();
                    alert('Pomodoro session complete!');
                } else {
                    requestAnimationFrame(updateTimer);
                }

                updateDisplay();
            }
        }

        function resetTimer() {
            isRunning = false;
            duration = parseInt(durationSelect.value) * 60;
            timeLeft = duration;
            updateDisplay();
            startBtn.textContent = 'Start';
            durationSelect.disabled = false;
            goalInput.disabled = false;
            currentSession = null;
        }

        function changeDuration() {
            if (!isRunning) {
                duration = parseInt(durationSelect.value) * 60;
                timeLeft = duration;
                updateDisplay();
            }
        }

        function endSession() {
            if (currentSession) {
                currentSession.endTime = new Date().toISOString();
                currentSession.duration = Math.round((new Date(currentSession.endTime) - new Date(currentSession.startTime)) / 1000);
                sessions.unshift(currentSession);
                updateSessionLog();
                saveSessions();
                resetTimer();
            }
        }

        function updateSessionLog() {
            sessionLogBody.innerHTML = '';
            sessions.forEach((session, index) => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${session.goal}</td>
                    <td>${formatDate(session.startTime)}</td>
                    <td>${session.endTime ? formatDate(session.endTime) : 'In progress'}</td>
                    <td>${formatDuration(session.duration)}</td>
                    <td>${formatPauses(session.pauses)}</td>
                    <td><button class="deleteBtn" data-index="${index}">❌</button></td>
                `;
                sessionLogBody.appendChild(row);
            });
            jsonOutput.value = JSON.stringify(sessions, null, 2);

            // Add event listeners to delete buttons
            document.querySelectorAll('.deleteBtn').forEach(btn => {
                btn.addEventListener('click', deleteSession);
            });
        }

        function deleteSession(event) {
            const index = parseInt(event.target.getAttribute('data-index'));
            sessions.splice(index, 1);
            updateSessionLog();
            saveSessions();
        }

        function formatDuration(seconds) {
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = seconds % 60;
            return `${minutes}m ${remainingSeconds}s`;
        }

        function formatPauses(pauses) {
            return pauses.map(pause => 
                `${formatDate(pause.pauseTime)} - ${pause.resumeTime ? formatDate(pause.resumeTime) : 'Not resumed'}`
            ).join('<br>');
        }

        function saveSessions() {
            if (isLocalStorageAvailable()) {
                localStorage.setItem('pomodoroSessions', JSON.stringify(sessions));
            }
        }

        startBtn.addEventListener('click', startTimer);
        resetBtn.addEventListener('click', resetTimer);
        endBtn.addEventListener('click', endSession);
        durationSelect.addEventListener('change', changeDuration);

        // Keyboard shortcut
        document.addEventListener('keydown', (e) => {
            if (e.code === 'Space' && document.activeElement !== goalInput) {
                e.preventDefault();
                startTimer();
            }
        });

        updateDisplay();
    </script>
</body>
</html>
